<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar
      fixed
      placeholder
      left-arrow
      @click-left="$router.back()"
      title="搜索中心"
    />
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 3.推荐词 -->
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        :title="item"
        icon="search"
        @click="$router.push({path:'/searchResult',query:{q:list[index]}})"
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 4.搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion} from "./home";
export default {
  name: "search",
  data() {
    return {
      value: "",
      list: [],
      timeID: null, //防抖定时器
    };
  },
  methods: {
    onSearch() {
      this.$router.push({path:'/searchResult',query:{q:this.value}})
    },
    onInput() {
      //清除上次定时器，以最后一次触发为准
      clearTimeout(this.timeID);
      //开启防抖定时器
      this.timeID = setTimeout(async () => {
        if (this.value == "") {
          this.list = [];
          return false;
        }
        let res = await getSuggestion(this.value);
        this.list = res.data.data.options;
      },500);
    },
  },
  computed: {
    showList() {
      //(1)创建正则 ： 全局匹配当前搜索框内容，  g:全局匹配  i:不区分大小写
      const reg = new RegExp(this.value, "ig");
      //(2)map隐射数组
      return this.list.map((item) => {
        //将搜索结果替换为<span>标签
        return item.replace(
          reg,
          (match) => `<span style="color: red;">${match}</span>`
        );
      });
    },
  },
};
</script>

<style>
</style>